import os
import sys
import galscript
from pydub import AudioSegment
from pydub.utils import mediainfo


class LilithPreProcessor(galscript.PreProcessor):
    def __init__(self, filename):
        super().__init__(filename)

    def pick_dialog(self):
        # 保存当前的项目
        text = self.current

        # 依次查找，直到下一个
        while True:
            if self.next() == False:
                break

            # 增加项目
            text += self.current + "\\n"

            # 检查当前的项目是不是结束
            if self.contain("[T_NEXT]\\"):
                break

        self.keep_text(text)

    def process_current(self):
        if self.startswith(";"):
            self.discard()
        elif self.startswith("*"):
            self.discard()
        elif self.startswith("[cm][SYSMENU]"):
            self.discard()
        elif self.startswith("[NAME_"):
            self.pick_dialog()
        else:
            self.keep()

        pass


class LilithScript(galscript.ScriptLine):
    def __init__(self, index, text, processor):
        super().__init__(index, text, processor)

    def check_pass(self):
        ignore_list = ["[BGM_S", "[BGM_FS"]
        for idx,value in enumerate(ignore_list):
          if self.is_prefix(value): return self.discard()
        return False

    def process_text(self):
        # 处理拥有声音的，进行合并
        if self.is_prefix("[VO"):
            # [VO vo="v_say0001"]\
            # [NAME_W n="沙代子"]\「よいしょ、と……」[T_NEXT]\\n

            # 提取出声音
            voice = self.find_str('vo="([^"]*)"')
            self.add_attr("VoiceFile", voice)

            # 处理下一行的议定
            next = self.processor.get(self.index + 1)
            text = ""
            if next and next.is_prefix("[NAME"):
                text = next.find_str(r"\]\\([^/]+?)\[T_NEXT")
                name = next.find_str('n="([^"]*)"')
                self.add_attr("Name", name)
                next.is_discard = True
            return self.save("Text", text)
        elif self.is_prefix("[NAME"):
            text = self.find_str(r"\]\\([^/]+?)\[T_NEXT")
            name = self.find_str('n="([^"]*)"')
            self.add_attr("Name", name)

            return self.save("Text", text)
        return False

    def process_picture(self):
        if self.is_prefix("[TR") or self.contain("bmp="):
            self.add_attr("ShowType", self.find_str('type="([^"]*)"'))
            file = self.find_str('bmp="([^"]*)"')
            return self.save("Bg", file)

        if self.is_prefix("[T_BMP") or self.contain("bmp_c="):
            file = self.find_str('bmp_c="([^"]*)"')
            place = self.find_int(r"place=(\d+)")
            self.add_attr("Slot", place)
            # 根据Place决定位置
            self.add_attr("Point", f"{place * 200},{0}")
            return self.save("Picture", file)

        if self.is_prefix("[T_FADEOUT"):
            slot = self.find_int(r"place=(\d+)")
            return self.save("Clear", slot)

        return False

    def process_sound(self):
        if self.is_prefix("[BGM"):
            file = self.find_str('bgm="([^"]*)"')
            return self.save("BGM", file)

        # 播放音效，这个好像是一个持续音效，那么用BGS来播放。
        if self.is_prefix("[playse"):
            file = self.find_quote_str("storage")
            return self.save("BGS", file)
        if self.is_prefix("[SE_STOP"):
            return self.set_command_xml("StopBGS")
        return False

    def process_command(self):
        if self.is_prefix("[wait time"):
            return self.save("Wait", self.find_equal_int("time"))
        return False

    def process(self):
        if self.is_discard:
            return
        if self.check_pass():
            return

        if self.process_text():
            return
        if self.process_picture():
            return
        if self.process_sound():
            return
        if self.process_command():
            return

        # 无法识别的项目
        self.save_undefined()

def process_file(input_file, assets_dir):
    # 预先处理项目（简化之后的处理）
    pre_processor = LilithPreProcessor(input_file)
    pre_processor.process()
    pre_processor.save()

    # 处理之后的项目
    processor = galscript.ScriptProcessor(
        pre_processor.output_file,
        lambda idx, name, processor: LilithScript(idx, name, processor),
    )
    processor.redirect_output(input_file)
    processor.assets_dir = assets_dir
    processor.process()
    processor.save()

    print(f"处理完成！结果已保存到: {processor.output_file}")

if __name__ == "__main__":
    args = galscript.FileManager()  # 使用imodule中的Args类
    args.foreach_file([".txt"], lambda file: process_file(file, args.assets_dir))


